package it.hopeless.jee6.registry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ejb.EJB;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.FileInputStream;
import java.util.Properties;

/**
 * User: frico
 * Date: Feb 6, 2010
 * Time: 7:18:14 PM
 */
@WebListener
public class StartupContextListener implements ServletContextListener {
    private static final Logger logger = LoggerFactory.getLogger(StartupContextListener.class);

    @EJB
    RegistryService registry;

    public void contextInitialized(ServletContextEvent servletContextEvent) {
        logger.info("Initializing registry from Web context startup");
        Properties fileProperties = new Properties();
        try {
            fileProperties.load(servletContextEvent.getServletContext().getResourceAsStream("/WEB-INF/classes/jee6.properties"));
            //loading application bundled properties
            registry.putAll(fileProperties);
            //loading external properties
            registry.putAll(loadExternalProperties(fileProperties.getProperty("jee6.external.configuration_properties_file")));
        } catch (Exception e) {
            logger.error("Error initializing file properties for registry",e);
        }
    }

    public Properties loadExternalProperties(String filePath){
        Properties externalProperties = new Properties();
        logger.debug("Loading external properties from file: "+ filePath);
        if(filePath != null){
            try {
                externalProperties.load(new FileInputStream(filePath));
            } catch (Exception e) {
                logger.error("External properties colud not be loaded", e);
            }
        }
        return externalProperties;
    }

    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    }
}
